<template>
  <div class="route-management">
    <!-- 筛选区 -->
    <el-form :model="filter" inline class="filter-bar">
      <el-form-item label="线路编号/名称">
        <el-input
          v-model="filter.keyword"
          placeholder="请输入线路编号或线路名称"
          clearable
          style="width: 220px"
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="filter.status" placeholder="请选择">
          <el-option label="全部" value="" />
          <el-option label="启用" value="启用" />
          <el-option label="禁用" value="禁用" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="queryData">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作栏 -->
    <div class="action-bar">
      <el-button type="primary" @click="openDialog('create')">新增</el-button>
      <el-button
        type="danger"
        @click="handleBatchDelete"
        :disabled="selectedRows.length === 0"
        >删除</el-button
      >
      <el-button type="info">导入</el-button>
      <el-button type="success">导出</el-button>
      <el-button @click="handleRefresh">刷新</el-button>
    </div>

    <!-- 线路表格 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 16px"
      :header-cell-style="{ background: '#F8F9FA' }"
      @selection-change="handleSelection"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column label="操作" width="80">
        <template #default="scope">
          <el-icon
            @click="openDialog('edit', scope.row)"
            style="cursor: pointer; margin-right: 8px"
          >
            <Edit />
          </el-icon>
          <el-icon
            @click="handleRowDelete(scope.row)"
            style="cursor: pointer; color: red"
          >
            <Delete />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="code" label="线路编号" min-width="120" sortable />
      <el-table-column prop="name" label="线路名称" min-width="120" sortable />
      <el-table-column label="状态" width="120">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="启用"
            inactive-value="禁用"
            @change="handleStatusToggle(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="默认" width="120">
        <template #default="scope">
          <el-switch
            v-model="scope.row.isDefault"
            active-text="是"
            inactive-text="否"
            @change="handleDefaultToggle(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="deliveryMan" label="送货员" min-width="120" />
      <el-table-column prop="driver" label="司机" min-width="120" />
      <el-table-column prop="licensePlate" label="车牌号" min-width="120" />
    </el-table>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.type === 'create' ? '新增线路' : '编辑线路'"
      width="500px"
    >
      <el-form
        :model="dialogForm"
        label-width="80px"
        :rules="formRules"
        ref="formRef"
      >
        <el-form-item label="线路编号" prop="code">
          <el-input v-model="dialogForm.code" placeholder="请输入线路编号" />
        </el-form-item>
        <el-form-item label="线路名称" prop="name">
          <el-input v-model="dialogForm.name" placeholder="请输入线路名称" />
        </el-form-item>
        <el-form-item label="车牌号">
          <el-input
            v-model="dialogForm.licensePlate"
            placeholder="请输入车牌号"
          />
        </el-form-item>
        <el-form-item label="送货员">
          <el-select
            v-model="dialogForm.deliveryMan"
            placeholder="请选择送货员"
          >
            <el-option
              v-for="item in userOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="司机">
          <el-select v-model="dialogForm.driver" placeholder="请选择司机">
            <el-option
              v-for="item in userOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="车辆类型">
          <el-input
            v-model="dialogForm.vehicleType"
            placeholder="请输入车辆类型"
          />
        </el-form-item>
        <el-form-item label="载重">
          <el-input v-model="dialogForm.load" placeholder="请输入载重" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            type="textarea"
            v-model="dialogForm.remark"
            placeholder="请输入备注内容"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="默认线路">
          <el-switch
            v-model="dialogForm.isDefault"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox, ElSwitch } from "element-plus";
import { Edit, Delete } from "@element-plus/icons-vue";

// ========== 筛选条件 ==========
const filter = reactive({
  keyword: "", // 线路编号/名称
  status: "", // 状态：''(全部)/启用/禁用
});

// ========== 弹窗状态 ==========
const dialog = reactive({
  visible: false,
  type: "create", // create/edit
  origin: {}, // 编辑时存储原始数据
});

// ========== 弹窗表单 ==========
const dialogForm = reactive({
  code: "",
  name: "",
  licensePlate: "",
  deliveryMan: "",
  driver: "",
  vehicleType: "",
  load: "",
  remark: "",
  isDefault: false,
});

// ========== 表单校验规则 ==========
const formRules = {
  code: [{ required: true, message: "请输入线路编号", trigger: "blur" }],
  name: [{ required: true, message: "请输入线路名称", trigger: "blur" }],
};

// ========== 表格数据 ==========
const tableData = ref([
  {
    code: "001",
    name: "线路1",
    status: "启用",
    isDefault: false,
    deliveryMan: "销售-小李",
    driver: "销售-小李",
    licensePlate: "0001",
  },
  {
    code: "002",
    name: "三峡人家",
    status: "启用",
    isDefault: false,
    deliveryMan: "",
    driver: "",
    licensePlate: "",
  },
]);

// ========== 选中数据 ==========
const selectedRows = ref([]);

// ========== 下拉选项 ==========
const userOptions = [
  "老板",
  "财务-玲",
  "采购-小陈",
  "采购-小王",
  "销售-小李",
  "销售-小东",
  "旗舰店店员",
  "2店店员",
  "1号仓库管员",
];

// ========== 核心方法 ==========
/** 查询数据（模拟） */
const queryData = () => {
  let filtered = tableData.value.filter((item) => {
    // 关键词匹配
    if (filter.keyword) {
      return (
        item.code.includes(filter.keyword) || item.name.includes(filter.keyword)
      );
    }
    return true;
  });
  // 状态匹配
  if (filter.status) {
    filtered = filtered.filter((item) => item.status === filter.status);
  }
  tableData.value = filtered;
  ElMessage.info("查询完成");
};

/** 打开弹窗（新增/编辑） */
const openDialog = (type, row) => {
  dialog.type = type;
  dialog.visible = true;
  if (type === "create") {
    // 新增：清空表单
    Object.keys(dialogForm).forEach((key) => {
      dialogForm[key] = "";
    });
    dialogForm.isDefault = false;
  } else {
    // 编辑：复制数据
    Object.assign(dialogForm, row);
    dialog.origin = { ...row }; // 保存原始数据
  }
};

/** 保存数据（新增/编辑） */
const handleSave = () => {
  // 校验表单
  if (!dialogForm.code || !dialogForm.name) {
    ElMessage.warning("线路编号和名称为必填项");
    return;
  }
  if (dialog.type === "create") {
    // 新增
    tableData.value.push({ ...dialogForm });
    ElMessage.success("新增线路成功");
  } else {
    // 编辑：对比原始数据，避免无变化提交
    if (JSON.stringify(dialogForm) === JSON.stringify(dialog.origin)) {
      ElMessage.info("未检测到数据变化");
      dialog.visible = false;
      return;
    }
    const index = tableData.value.findIndex(
      (item) => item.code === dialog.origin.code
    );
    tableData.value[index] = { ...dialogForm };
    ElMessage.success("编辑线路成功");
  }
  dialog.visible = false;
};

/** 批量删除 */
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要删除的线路");
    return;
  }
  ElMessageBox.confirm("确定删除选中的线路吗？", "警告", { type: "warning" })
    .then(() => {
      tableData.value = tableData.value.filter(
        (item) => !selectedRows.value.some((sel) => sel.code === item.code)
      );
      selectedRows.value = [];
      ElMessage.success("删除成功");
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

/** 单行删除（操作列） */
const handleRowDelete = (row) => {
  ElMessageBox.confirm("确定删除该线路吗？", "警告", { type: "warning" })
    .then(() => {
      tableData.value = tableData.value.filter(
        (item) => item.code !== row.code
      );
      ElMessage.success("删除成功");
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

/** 状态切换（启用/禁用） */
const handleStatusToggle = (row) => {
  ElMessage.success(`线路 ${row.name} 状态已切换为 ${row.status}`);
};

/** 默认线路切换（确保唯一） */
const handleDefaultToggle = (row) => {
  if (row.isDefault) {
    // 取消其他线路的默认
    tableData.value.forEach((item) => {
      if (item.code !== row.code) {
        item.isDefault = false;
      }
    });
    ElMessage.success("已设置为默认线路");
  }
};

/** 刷新数据 */
const handleRefresh = () => {
  // 模拟恢复初始数据（实际调用接口）
  tableData.value = [
    {
      code: "001",
      name: "线路1",
      status: "启用",
      isDefault: false,
      deliveryMan: "销售-小李",
      driver: "销售-小李",
      licensePlate: "0001",
    },
    {
      code: "002",
      name: "三峡人家",
      status: "启用",
      isDefault: false,
      deliveryMan: "",
      driver: "",
      licensePlate: "",
    },
  ];
  ElMessage.success("数据已刷新");
};

/** 选中行变化 */
const handleSelection = (val) => {
  selectedRows.value = val;
};
</script>

<style scoped>
.route-management {
  padding: 24px;
  background: #fff;
}

.filter-bar {
  margin-bottom: 16px;
}

.action-bar {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.dialog-footer {
  text-align: right;
}

/* 操作图标样式 */
.el-icon {
  font-size: 18px;
  cursor: pointer;
}
</style>